import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _class, _class2;

import React from 'react';
import { Button, Col, DatePicker, Form, Modal, Popconfirm, Row, Select, Table } from 'antd';
import { Bind } from 'lodash-decorators';
import moment from 'moment';
import { Button as ButtonPermission } from 'components/Permission';
import intl from 'utils/intl';
import { getDateTimeFormat, isTenantRoleLevel, tableScrollWidth } from 'utils/utils';
import { dateTimeRender, TagRender, operatorRender } from 'utils/renderer';
import { CPAAS_FILE, BKT_SDR } from 'utils/config';
import notification from 'utils/notification';
import { DEFAULT_DATETIME_FORMAT, SEARCH_FORM_ROW_LAYOUT } from 'utils/constants';
import { downloadFile } from 'cpaas-front/lib/services/api';
import ProgressModal from "../components/ProgressModal";
var formLayout = {
  labelCol: {
    span: 11
  },
  wrapperCol: {
    span: 13
  }
};
var LogDrawer = (_dec = Form.create({
  fieldNameProp: null
}), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), _dec11 = Bind(), _dec12 = Bind(), _dec(_class = (_class2 = /*#__PURE__*/function (_React$Component) {
  _inherits(LogDrawer, _React$Component);

  var _super = _createSuper(LogDrawer);

  function LogDrawer() {
    var _this;

    _classCallCheck(this, LogDrawer);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      tenantRoleLevel: isTenantRoleLevel(),
      progressVisible: false,
      progressValue: {}
    };
    _this.progressTimer = void 0;
    return _this;
  }

  _createClass(LogDrawer, [{
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.clearProgressTimer();
    } // 清除进度获取定时器

  }, {
    key: "clearProgressTimer",
    value: function clearProgressTimer() {
      clearInterval(this.progressTimer);
      this.progressTimer = null;
    }
  }, {
    key: "showErrorModal",
    value: function showErrorModal(record) {
      var _this$props$onError = this.props.onError,
          onError = _this$props$onError === void 0 ? function (e) {
        return e;
      } : _this$props$onError;
      onError({
        logId: record.logId
      });
    }
  }, {
    key: "handleSearch",
    value: function handleSearch() {
      var _this$props = this.props,
          form = _this$props.form,
          _this$props$onSearch = _this$props.onSearch,
          onSearch = _this$props$onSearch === void 0 ? function (e) {
        return e;
      } : _this$props$onSearch;
      var fieldsValue = form.getFieldsValue();
      fieldsValue.timeStart = fieldsValue.timeStart && fieldsValue.timeStart.format(DEFAULT_DATETIME_FORMAT);
      fieldsValue.timeEnd = fieldsValue.timeEnd && fieldsValue.timeEnd.format(DEFAULT_DATETIME_FORMAT);
      onSearch(fieldsValue);
    }
  }, {
    key: "handleReset",
    value: function handleReset() {
      var form = this.props.form;
      form.resetFields();
    }
  }, {
    key: "showLogModal",
    value: function showLogModal(record) {
      var onFetchLogDetail = this.props.onFetchLogDetail;
      onFetchLogDetail(record);
    }
    /**
     * 下载
     * @param {object} record - 流程对象
     */

  }, {
    key: "downloadLogFile",
    value: function downloadLogFile(record) {
      var tenantId = record.tenantId;
      var tenantRoleLevel = this.state.tenantRoleLevel;
      var api = tenantRoleLevel ? "".concat(CPAAS_FILE, "/v1/").concat(tenantId, "/files/download") : "".concat(CPAAS_FILE, "/v1/files/download");

      if (record.logFlag === 1) {
        this.showLogModal(record);
      }

      if (record.logFlag === 0 && record.logUrl !== '') {
        downloadFile({
          requestUrl: api,
          queryParams: [{
            name: 'bucketName',
            value: BKT_SDR
          }, {
            name: 'directory',
            value: 'csdr01'
          }, {
            name: 'url',
            value: record.logUrl
          }]
        });
      }
    }
  }, {
    key: "handleDeleteContent",
    value: function handleDeleteContent(record) {
      var _this$props$onDelete = this.props.onDelete,
          onDelete = _this$props$onDelete === void 0 ? function (e) {
        return e;
      } : _this$props$onDelete;
      onDelete(record);
    }
  }, {
    key: "handleTableChange",
    value: function handleTableChange(page) {
      var _this$props$onSearch2 = this.props.onSearch,
          onSearch = _this$props$onSearch2 === void 0 ? function (e) {
        return e;
      } : _this$props$onSearch2;
      onSearch({
        page: page
      });
    }
    /**
     * @function renderForm - 渲染搜索表单
     */

  }, {
    key: "renderFilterForm",
    value: function renderFilterForm() {
      var _this$props2 = this.props,
          _this$props2$form = _this$props2.form,
          getFieldDecorator = _this$props2$form.getFieldDecorator,
          getFieldValue = _this$props2$form.getFieldValue,
          _this$props2$jobLogLd = _this$props2.jobLogLdp,
          jobLogLdp = _this$props2$jobLogLd === void 0 ? {} : _this$props2$jobLogLd;
      var dateTimeFormat = getDateTimeFormat();
      var _jobLogLdp$jobResultL = jobLogLdp.jobResultList,
          jobResultList = _jobLogLdp$jobResultL === void 0 ? [] : _jobLogLdp$jobResultL,
          _jobLogLdp$clientResu = jobLogLdp.clientResultList,
          clientResultList = _jobLogLdp$clientResu === void 0 ? [] : _jobLogLdp$clientResu;
      return /*#__PURE__*/React.createElement(Form, {
        className: "more-fields-form"
      }, /*#__PURE__*/React.createElement(Row, SEARCH_FORM_ROW_LAYOUT, /*#__PURE__*/React.createElement(Col, {
        span: 18
      }, /*#__PURE__*/React.createElement(Row, SEARCH_FORM_ROW_LAYOUT, /*#__PURE__*/React.createElement(Col, {
        span: 8
      }, /*#__PURE__*/React.createElement(Form.Item, Object.assign({
        label: intl.get('csdr.jobLog.model.jobLog.jobResult').d('调度结果')
      }, formLayout), getFieldDecorator('jobResult')( /*#__PURE__*/React.createElement(Select, {
        allowClear: true
      }, jobResultList.map(function (item) {
        return /*#__PURE__*/React.createElement(Select.Option, {
          value: item.value,
          key: item.value
        }, item.meaning);
      }))))), /*#__PURE__*/React.createElement(Col, {
        span: 8
      }, /*#__PURE__*/React.createElement(Form.Item, Object.assign({
        label: intl.get('csdr.jobLog.model.jobLog.clientResult').d('客户端执行结果')
      }, formLayout), getFieldDecorator('clientResult')( /*#__PURE__*/React.createElement(Select, {
        allowClear: true
      }, clientResultList.map(function (item) {
        return /*#__PURE__*/React.createElement(Select.Option, {
          value: item.value,
          key: item.value
        }, item.meaning);
      }))))), /*#__PURE__*/React.createElement(Col, {
        span: 8
      }, /*#__PURE__*/React.createElement(Form.Item, Object.assign({
        label: intl.get('csdr.jobLog.model.jobLog.startTime').d('执行开始时间')
      }, formLayout), getFieldDecorator('timeStart')( /*#__PURE__*/React.createElement(DatePicker, {
        showTime: true,
        format: dateTimeFormat,
        placeholder: "",
        disabledDate: function disabledDate(currentDate) {
          return getFieldValue('timeEnd') && moment(getFieldValue('timeEnd')).isBefore(currentDate, 'day');
        }
      }))))), /*#__PURE__*/React.createElement(Row, SEARCH_FORM_ROW_LAYOUT, /*#__PURE__*/React.createElement(Col, {
        span: 8
      }, /*#__PURE__*/React.createElement(Form.Item, Object.assign({
        label: intl.get('csdr.jobLog.model.jobLog.completeTime').d('结束时间')
      }, formLayout), getFieldDecorator('timeEnd')( /*#__PURE__*/React.createElement(DatePicker, {
        showTime: true,
        format: dateTimeFormat,
        placeholder: "",
        disabledDate: function disabledDate(currentDate) {
          return getFieldValue('timeStart') && moment(getFieldValue('timeStart')).isAfter(currentDate, 'day');
        }
      })))))), /*#__PURE__*/React.createElement(Col, {
        span: 6,
        className: "search-btn-more"
      }, /*#__PURE__*/React.createElement(Form.Item, null, /*#__PURE__*/React.createElement(Button, {
        style: {
          marginRight: 8
        },
        onClick: this.handleReset
      }, intl.get('cpaas.common.button.reset').d('重置')), /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        htmlType: "submit",
        onClick: this.handleSearch
      }, intl.get('cpaas.common.button.search').d('查询'))))));
    } // 获取任务进度

  }, {
    key: "fetchProgress",
    value: function fetchProgress(record) {
      var _this2 = this;

      var dispatch = this.props.dispatch;
      dispatch({
        type: 'jobInfo/fetchProgress',
        payload: {
          logId: record.logId
        }
      }).then(function (res) {
        if (res) {
          _this2.setState({
            progressValue: JSON.parse(res)
          });

          if (res === 100) {
            _this2.clearProgressTimer();

            notification.info({
              message: intl.get('csdr.jobLog.model.jobLog.showInfo').d('任务已执行完成！')
            });
          }
        }
      });
    } // 打开任务进度弹窗

  }, {
    key: "showProgressModal",
    value: function showProgressModal(record) {
      var _this3 = this;

      this.setState({
        progressVisible: true
      }, function () {
        _this3.fetchProgress(record);

        _this3.progressTimer = setInterval(function () {
          return _this3.fetchProgress(record);
        }, 5000);
      });
    } // 关闭任务进度弹窗

  }, {
    key: "closeProgressModal",
    value: function closeProgressModal() {
      var _this4 = this;

      var _this$props3 = this.props,
          onSearch = _this$props3.onSearch,
          jobPagination = _this$props3.jobPagination,
          form = _this$props3.form;
      this.setState({
        progressVisible: false
      }, function () {
        _this4.clearProgressTimer();

        onSearch(_objectSpread({
          page: jobPagination.current - 1,
          size: jobPagination.pageSize
        }, form.getFieldsValue()));
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this5 = this;

      var _this$props4 = this.props,
          title = _this$props4.title,
          modalVisible = _this$props4.modalVisible,
          initLoading = _this$props4.initLoading,
          onCancel = _this$props4.onCancel,
          path = _this$props4.path,
          _this$props4$jobLogLi = _this$props4.jobLogList,
          jobLogList = _this$props4$jobLogLi === void 0 ? [] : _this$props4$jobLogLi,
          _this$props4$jobPagin = _this$props4.jobPagination,
          jobPagination = _this$props4$jobPagin === void 0 ? {} : _this$props4$jobPagin;
      var _this$state = this.state,
          progressVisible = _this$state.progressVisible,
          progressValue = _this$state.progressValue;
      var progressProps = {
        progressVisible: progressVisible,
        progressValue: progressValue,
        onOk: this.closeProgressModal
      };
      var columns = [{
        title: intl.get('csdr.jobLog.model.jobLog.tenantName').d('租户'),
        width: 150,
        dataIndex: 'tenantName'
      }, {
        title: intl.get('csdr.jobLog.model.jobLog.jobResult').d('调度结果'),
        width: 100,
        dataIndex: 'jobResultMeaning',
        render: function render(text, record) {
          var statusList = [{
            status: 'SUCCESS',
            color: 'green'
          }, {
            status: 'FAILURE',
            color: 'red'
          }, {
            status: 'DOING',
            color: ''
          }];
          return TagRender(record.jobResult, statusList, text);
        }
      }, {
        title: intl.get('csdr.jobLog.model.jobLog.clientResult').d('客户端执行结果'),
        dataIndex: 'clientResultMeaning',
        width: 150,
        render: function render(text, record) {
          var statusList = [{
            status: 'SUCCESS',
            color: 'green'
          }, {
            status: 'FAILURE',
            color: 'red'
          }, {
            status: 'WARNING',
            color: 'orange'
          }, {
            status: 'DOING',
            color: ''
          }];
          return TagRender(record.clientResult, statusList, text);
        }
      }, {
        title: intl.get('csdr.jobLog.model.jobLog.executorName').d('执行器名称'),
        dataIndex: 'executorName',
        width: 150
      }, {
        title: intl.get('csdr.jobLog.model.jobLog.address').d('执行地址'),
        dataIndex: 'address',
        width: 200
      }, {
        title: intl.get('csdr.jobLog.model.jobLog.startTime').d('执行开始时间'),
        width: 150,
        dataIndex: 'startTime',
        render: dateTimeRender
      }, {
        title: intl.get('csdr.jobLog.model.jobLog.endTime').d('执行结束时间'),
        width: 150,
        dataIndex: 'endTime',
        render: dateTimeRender
      }, {
        title: intl.get('csdr.jobLog.model.jobLog.message').d('错误信息'),
        dataIndex: 'messageHeader',
        width: 250
      }, {
        title: intl.get('cpaas.common.button.action').d('操作'),
        width: 220,
        dataIndex: 'operator',
        fixed: 'right',
        render: function render(text, record) {
          var operators = [];

          if (record.clientResult === 'FAILURE') {
            operators.push({
              key: 'errorDetail',
              ele: /*#__PURE__*/React.createElement(ButtonPermission, {
                type: "text",
                permissionList: [{
                  code: "".concat(path, ".button.errorDetail"),
                  type: 'button',
                  meaning: '调度任务-错误详情'
                }],
                onClick: function onClick() {
                  return _this5.showErrorModal(record);
                }
              }, intl.get('csdr.jobLog.model.jobLog.errorDetail').d('错误详情')),
              len: 4,
              title: intl.get('csdr.jobLog.model.jobLog.errorDetail').d('错误详情')
            });
          }

          if (record.logUrl && record.logFlag === 0 || record.logFlag === 1) {
            operators.push({
              key: 'logDetail',
              ele: /*#__PURE__*/React.createElement(ButtonPermission, {
                type: "text",
                permissionList: [{
                  code: "".concat(path, ".button.logUrl"),
                  type: 'button',
                  meaning: '调度任务-日志文件'
                }],
                onClick: function onClick() {
                  return _this5.downloadLogFile(record);
                }
              }, record.logFlag === 1 ? intl.get('csdr.jobLog.model.jobLog.logDetail').d('日志详情') : intl.get('csdr.jobLog.model.jobLog.logUrl').d('日志文件')),
              len: 4,
              title: record.logFlag === 1 ? intl.get('csdr.jobLog.model.jobLog.logDetail').d('日志详情') : intl.get('csdr.jobLog.model.jobLog.logUrl').d('日志文件')
            });
          }

          if (record.clientResult === 'DOING') {
            operators.push({
              key: 'taskProgress',
              ele: /*#__PURE__*/React.createElement(ButtonPermission, {
                type: "text",
                permissionList: [{
                  code: "".concat(path, ".button.taskProgress"),
                  type: 'button',
                  meaning: '调度任务-任务进度'
                }],
                onClick: function onClick() {
                  return _this5.showProgressModal(record);
                }
              }, intl.get('csdr.jobLog.model.jobLog.taskProgress').d('任务进度')),
              len: 4,
              title: intl.get('csdr.jobLog.model.jobLog.taskProgress').d('任务进度')
            });
          }

          operators.push({
            key: 'delete',
            ele: /*#__PURE__*/React.createElement(Popconfirm, {
              placement: "topRight",
              title: intl.get('cpaas.common.message.confirm.delete').d('是否删除此条记录？'),
              onConfirm: function onConfirm() {
                return _this5.handleDeleteContent(record);
              }
            }, /*#__PURE__*/React.createElement(ButtonPermission, {
              type: "text",
              permissionList: [{
                code: "".concat(path, ".button.delete"),
                type: 'button',
                meaning: '调度任务-删除'
              }]
            }, intl.get('cpaas.common.button.delete').d('删除'))),
            len: 2,
            title: intl.get('cpaas.common.button.delete').d('删除')
          });
          return operatorRender(operators, record, {
            limit: 3
          });
        }
      }].filter(function (col) {
        return isTenantRoleLevel() ? col.dataIndex !== 'tenantName' : true;
      });
      return /*#__PURE__*/React.createElement(Modal, {
        destroyOnClose: true,
        wrapClassName: "ant-modal-sidebar-right",
        transitionName: "move-right",
        title: title,
        width: 1000,
        visible: modalVisible,
        onCancel: onCancel,
        footer: false
      }, /*#__PURE__*/React.createElement("div", {
        className: "table-list-search"
      }, this.renderFilterForm()), /*#__PURE__*/React.createElement(Table, {
        bordered: true,
        rowKey: "logId",
        loading: initLoading,
        dataSource: jobLogList,
        columns: columns,
        scroll: {
          x: tableScrollWidth(columns)
        },
        pagination: jobPagination,
        onChange: this.handleTableChange
      }), progressVisible && /*#__PURE__*/React.createElement(ProgressModal, progressProps));
    }
  }]);

  return LogDrawer;
}(React.Component), (_applyDecoratedDescriptor(_class2.prototype, "clearProgressTimer", [_dec2], Object.getOwnPropertyDescriptor(_class2.prototype, "clearProgressTimer"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "showErrorModal", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "showErrorModal"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleSearch", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "handleSearch"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleReset", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "handleReset"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "showLogModal", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "showLogModal"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "downloadLogFile", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "downloadLogFile"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleDeleteContent", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "handleDeleteContent"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleTableChange", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "handleTableChange"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "fetchProgress", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "fetchProgress"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "showProgressModal", [_dec11], Object.getOwnPropertyDescriptor(_class2.prototype, "showProgressModal"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "closeProgressModal", [_dec12], Object.getOwnPropertyDescriptor(_class2.prototype, "closeProgressModal"), _class2.prototype)), _class2)) || _class);
export { LogDrawer as default };